Page({
  data: {
    showInput: false,
    deviceNumber: '',
    managerName: '',
    isLoading: false
  },

  handleScanQRCode() {
    wx.scanCode({
      success: (res) => {
        const deviceInfo = this.parseQRCode(res.result);
        if (deviceInfo) {
          this.setData({
            showInput: true,
            deviceNumber: deviceInfo.deviceNumber || '',
            managerName: deviceInfo.managerName || ''
          });
        } else {
          wx.showToast({
            title: '无效的二维码',
            icon: 'error'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '扫码失败',
          icon: 'error'
        });
      }
    });
  },

  handleManualInput() {
    this.setData({
      showInput: true,
      deviceNumber: '',
      managerName: ''
    });
  },

  handleDeviceNumberInput(e) {
    this.setData({
      deviceNumber: e.detail.value
    });
  },

  handleManagerNameInput(e) {
    this.setData({
      managerName: e.detail.value
    });
  },

  async handleSubmit() {
    if (!this.validateInput()) {
      return;
    }

    this.setData({ isLoading: true });

    try {
      const result = await this.bindDevice({
        deviceNumber: this.data.deviceNumber,
        managerName: this.data.managerName
      });

      // 保存设备信息到本地存储
      wx.setStorageSync('deviceInfo', {
        deviceNumber: this.data.deviceNumber,
        managerId: this.data.managerName,
        bindTime: new Date().toISOString()
      });

      wx.showToast({
        title: '绑定成功',
        icon: 'success'
      });

      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    } catch (error) {
      wx.showToast({
        title: error.message || '绑定失败',
        icon: 'error'
      });
    } finally {
      this.setData({ isLoading: false });
    }
  },

  validateInput() {
    const deviceNumber = this.data.deviceNumber.trim();
    const managerName = this.data.managerName.trim();

    if (!deviceNumber) {
      wx.showToast({
        title: '请输入设备编号',
        icon: 'none'
      });
      return false;
    }

    if (!deviceNumber.startsWith('250724') || deviceNumber.length !== 10) {
      wx.showToast({
        title: '设备号必须以250724开头且为10位数',
        icon: 'none'
      });
      return false;
    }

    if (!managerName) {
      wx.showToast({
        title: '请输入管理员ID',
        icon: 'none'
      });
      return false;
    }

    const managerId = parseInt(managerName);
    if (isNaN(managerId) || managerId < 301 || managerId > 399) {
      wx.showToast({
        title: '管理员ID必须为301-399之间的数字',
        icon: 'none'
      });
      return false;
    }

    return true;
  },

  parseQRCode(qrContent) {
    try {
      // 模拟二维码数据
      return {
        deviceNumber: '2507240001',
        managerName: '301'
      };
    } catch (error) {
      console.error('解析二维码失败:', error);
      return null;
    }
  },

  async bindDevice(deviceInfo) {
    return new Promise((resolve, reject) => {
      // 验证设备号格式
      if (!deviceInfo.deviceNumber.startsWith('250724') || deviceInfo.deviceNumber.length !== 10) {
        reject(new Error('设备号格式错误，必须以250724开头且为10位数'));
        return;
      }

      // 验证管理员ID格式
      const managerId = parseInt(deviceInfo.managerName);
      if (isNaN(managerId) || managerId < 301 || managerId > 399) {
        reject(new Error('管理员ID格式错误，必须为301-399之间的数字'));
        return;
      }

      // 模拟异步操作
      setTimeout(() => {
        // 模拟成功响应
        resolve({
          success: true,
          data: {
            deviceNumber: deviceInfo.deviceNumber,
            managerId: deviceInfo.managerName,
            bindTime: new Date().toISOString()
          }
        });
      }, 1000); // 模拟1秒的网络延迟
    });
  }
}); 